#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>

void ChildRead(int rfd)
{
    // sleep(100);
    char buffer[1024];
    while (true)
    {
        ssize_t n = read(rfd, buffer, sizeof(buffer));
        if (n > 0)
        {
            // buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
    }
}
void FatherWrite(int wfd)
{
    char buffer[1024];
    int cnt = 0;
    while (true)
    {
        // const char* str = "i am father";
        snprintf(buffer, sizeof(buffer), "i am father 第%d次", cnt++);
        ssize_t n = write(wfd, buffer, sizeof(buffer));
        if (n < 0)
        {
            std::cout << "发送失败" << std::endl;
        }
        else if (n > 0)
        {
            std::cout << "发送成功" << std::endl;
        }
        sleep(1);
    }
}

int main()
{
    // 1. 创建通信信道
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    if (n < 0)
        return -1;

    // 2. 创建子进程
    pid_t pid = fork();
    if (pid == 0)
    {
        // 3. 父写子读 关闭对应文件描述符
        // child
        close(pipefd[1]);
        ChildRead(pipefd[0]);
        close(pipefd[0]);
        exit(1);
    }
    else if (pid < 0)
        return -1;
    // 3. 父写子读 关闭对应文件描述符

    // father
    close(pipefd[0]);
    FatherWrite(pipefd[1]);

    return 0;
}